package com.example.common.network;

public class ApiException extends Exception {
    
    private int code;
    private String message;
    
    public ApiException(int code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }
    
    public ApiException(String message) {
        super(message);
        this.message = message;
    }
    
    public ApiException(Throwable cause) {
        super(cause);
        this.message = cause.getMessage();
    }
    
    public int getCode() {
        return code;
    }
    
    public void setCode(int code) {
        this.code = code;
    }
    
    @Override
    public String getMessage() {
        return message;
    }
    
    public void setMessage(String message) {
        this.message = message;
    }
    
    public static ApiException handleException(Throwable e) {
        ApiException ex;
        if (e instanceof ApiException) {
            ex = (ApiException) e;
        } else if (e instanceof java.net.ConnectException) {
            ex = new ApiException(-1001, "网络连接异常，请检查网络");
        } else if (e instanceof java.net.SocketTimeoutException) {
            ex = new ApiException(-1002, "网络连接超时");
        } else if (e instanceof java.net.UnknownHostException) {
            ex = new ApiException(-1003, "网络异常，请检查网络");
        } else {
            ex = new ApiException(-1000, "未知错误：" + e.getMessage());
        }
        return ex;
    }
}